<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends Controller{
	// 过滤掉emoji表情
	function filterEmoji($str){
		$str = preg_replace_callback(
		'/./u',
		function (array $match) {
		return strlen($match[0]) >= 4 ? '' : $match[0];
		},
		$str);
		return $str;
	}

	public function index(){
		dump($_GET);
	}	

	//初始化
	public function redirect_url(){
		//微信信息
		$weixin = M('wx')->find();
	    $appid = $weixin['appid'];
	    $secret = $weixin['appsecret'];
	    $state = I('state','inquerycard');
	    $redirect_uri = 'http://wxtools.chedai0.com/index.php/Weixin/Index/redirect_url';
	    /*----------微信授权------------*/
	    if(empty(I('code'))){
	    	$url = 'http://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.
	    	urlencode($redirect_uri).'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect ';
		    header('Location: '.$url);
	    }else{
	       /*----------获取openid和微信资料------------*/
	       $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.I('code').'&grant_type=authorization_code';
	       $curl = new \Util\Curl();
	       $result = $curl->http_get($url);
		   $data = json_decode($result,true);  
	       $access_token = $data['access_token'];
	       $openid =  $data['openid'];	
	       /*--------获取个人信息---------------------*/
	       	if($openid){
			    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
			    $result = $curl->http_get($url);   
			    $data = json_decode($result,true);
			    //重定向
			    if($data['errcode'] == '48001'){
			  	  $url = 'http://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.
			  	  urlencode($redirect_uri).'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect';
			      header('Location: '.$url);
			    }
		        $nickname = $data["nickname"];
			    $avatar = $data["headimgurl"]; 
			    if($nickname){
				   	$user = M('user');
				   	$where = array();
				   	$where['openid'] = $openid;
				   	$user_data = array();
				   	$user_data["openid"] = $openid;
				   	$user_data["nickname"] = $this->filterEmoji($nickname);
				   	$user_data["headimgurl"] = $avatar;
				  	$user_data["ctime"] = time();
				  	//判断是否该用户是否存在,存在则更新信息
				    $userinfo=$user->where($where)->find();
				    if ($userinfo) {
				        unset($user_data['ctime']);
				        file_put_contents('user.txt',var_export($user_data,true));
				        $uid=M('user')->where($where)->save($user_data);
				        if($uid !== false){
				        	$uid = $userinfo['user_id'];
				        }
			    	}else{
			    		file_put_contents('user.txt',var_export($user_data,true));
			       	    $uid = $user->add($user_data);   
			    	}
				}
				if($uid !== false){
			   		session("uid",$uid);
			   		if($state == 'inqueryCard'){
			   			header('Location: http://'.$_SERVER['HTTP_HOST'].'/index.php/Weixin/Card/inquery');
			   		}elseif($state == 'bindUser'){
			   			header('Location: http://'.$_SERVER['HTTP_HOST'].'/index.php/Weixin/User/bind');
			   		}elseif($state == 'indexUser'){
			   			header('Location: http://'.$_SERVER['HTTP_HOST'].'/index.php/Weixin/User/index');
			   		}   
			   	}else{
				    echo "提交失败";
				}    
			}
			
	    } 
	}
}